package manage

import (
	"os"

	"github.com/gofiber/fiber/v2"
	logger "github.com/sirupsen/logrus"

	"publish-manage/internal/model"
	"publish-manage/internal/service"
	"publish-manage/pkg/constant"
	"publish-manage/pkg/domain"
	"publish-manage/pkg/server"
	"publish-manage/pkg/util"
)

var AgentRequestController = new(agentRequestController)

type agentRequestController struct{}

func (c *agentRequestController) GetPackage(ctx *fiber.Ctx) error {
	sig := ctx.Get(fiber.HeaderAuthorization)
	agentId := ctx.Query("agentId")
	packageId := ctx.Query("packageId")

	if agentId == "" || packageId == "" {
		ctx.Status(fiber.StatusPreconditionFailed)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorParamRequired,
			Msg:  "代理及发布包的id必须提供",
		})
	}

	if sig != util.HmacSha256(packageId, agentId) {
		return fiber.ErrForbidden
	}

	agent, err := service.AgentService.Get(&model.Agent{Id: agentId})
	if err != nil {
		logger.Error(err)
		ctx.Status(fiber.StatusInternalServerError)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorInternal,
			Msg:  "获取代理信息出错",
		})
	}

	if agent == nil {
		ctx.Status(fiber.StatusPreconditionFailed)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorResourceNotFound,
			Msg:  "代理信息未找到",
		})
	}
	if agent.Ip != server.GetClientIp(ctx) {
		ctx.Status(fiber.StatusPreconditionFailed)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorDataNotMatch,
			Msg:  "代理IP不匹配",
		})
	}

	p, err := service.PackageVersionService.GetLatest(packageId)
	if err != nil {
		logger.Error(err)
		ctx.Status(fiber.StatusInternalServerError)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorInternal,
			Msg:  "获取代理信息出错",
		})
	}
	if p == nil {
		ctx.Status(fiber.StatusPreconditionFailed)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorResourceNotFound,
			Msg:  "部署信息未找到",
		})
	}

	// 返回文件
	file, err := os.Open(p.Path)
	if err != nil {
		logger.Error(err)
		ctx.Status(fiber.StatusInternalServerError)
		return ctx.JSON(&domain.CommonResponse{
			Code: constant.ResponseCodeErrorInternal,
			Msg:  "读取部署文件信息出错",
		})
	}

	return ctx.SendStream(file)
}
